<template>
	<view>
		<button type="primary" style="width: 100%;" @click="createBLE">创建服务模式(从机广播)</button>
		<button type="primary" style="width: 100%;margin-top: 5px;" @click="stopAdvertising">停止广播</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				Slave: '',
				server: null, //建立本地服务端返回的对象
				value: '', //写的数据
			}
		},
		// 生命周期函数--监听页面加载
		onLoad() {
			var res = wx.getSystemInfoSync()
			if (res.platform == 'android') {
				console.log('机型：android');
				this.openBluetoothed()
			} else {
				console.log('111');
			}
			// 监听蓝牙设备连接状态变化
			wx.onBLEPeripheralConnectionStateChanged((res) => {
				console.log("连接成功后的返回值")
				if (res.connected) {
					wx.showToast({
						title: '蓝牙设备已连接',
						icon: 'success'
					})
				} else {
					wx.showToast({
						title: '蓝牙设备已断开',
						icon: 'success'
					})
				}
			});
		},
		onHide() {
			this.stopAdvertising()
		},
		methods: {
			// 初始化蓝牙模块。iOS 上开启主机/从机（外围设备）模式时需分别调用一次，并指定对应的 mode。
			openBluetoothed() {
				wx.openBluetoothAdapter({
					mode: "peripheral",
					success(res) {
						console.log("成功:" + res.errMsg)
						// 获取本机蓝牙适配器状态。
						wx.getBluetoothAdapterState({
							success(res) {
								console.log("是否正在搜索设备:" + res.discovering)
								console.log("蓝牙适配器是否可用:" + res.available)
							}
						})
					}
				})
			},
			// 创建从机服务端
			createBLE() {
				let _this = this
				wx.createBLEPeripheralServer({
					success: (res) => {
						_this.Slave="成功"
						_this.server=res.server
						if (res.errMsg == "createBLEPeripheralServer:ok") {
							wx.showToast({
								title: '创建成功',
								icon: 'success'
							})
						}
						res.server.addService({
							service: {
								uuid: "000018f0-0000-1000-8000-00805f9b34fb",
								characteristics: [{
										uuid: "00002af0-0000-1000-8000-00805f9b34fb",
										properties: {
											read: true,
											notify: true
										},
										permission: {
											readable: true
										},
										value: _this.string2buffer("1234"),
									},
									{
										uuid: "00002af1-0000-1000-8000-00805f9b34fb",
										properties: {
											writeNoResponse: true,
											extendedProperties: true
										},
										permission: {
											writeable: true
										},
										value: _this.string2buffer("4321"),
									}
								]
							},
							success(res) {
								console.log('添加服务成功:', res);
								_this.setOnRequest(); //监听读写操作
								_this.startAdvertising(); //开启广播
							},
							fail(err) {
								console.log('添加服务失败:', err)
							}
						});
					}
				})
			},
			setOnRequest() {
				var that = this;
				console.log("设置监听读写");
				if (that.server) {
					that.server.onCharacteristicWriteRequest(function callback(res) {
						console.log('写入请求监听')
						console.log("写入的数据:" + that.buf2string(res.value))
						that.value=that.buf2string(res.value)
						that.server.writeCharacteristicValue({
							serviceId: res.serviceId,
							characteristicId: res.characteristicId,
							value: res.value,
							needNotify: true,
							callbackId: res.callbackId
						})
					})
					that.server.onCharacteristicReadRequest(function callback(res) {
						console.log('读取请求监听')
						that.server.writeCharacteristicValue({
							serviceId: res.serviceId,
							characteristicId: res.characteristicId,
							value: that.string2buffer("5555"),
							needNotify: true,
							callbackId: res.callbackId
						})
					})
				}
			},
			buf2string(buffer) {
				var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
				var str = ''
				for (var i = 0; i < arr.length; i++) {
					str += String.fromCharCode(arr[i])
				}
				return str
			},
			
			startAdvertising() {
				
				this.server.startAdvertising({
					advertiseRequest: {
						deviceName: "0804",
						serviceUuids: ["000018f0-0000-1000-8000-00805f9b34fb"]
					},
					powerLevel: 'high',
					success: res => {
						if (res.errMsg == "startBLEPeripheralAdvertising:ok") {
							wx.showToast({
								title: '已开启广播',
								icon: 'success'
							})
						}

					},

					fail: error => {
						console.log("startAdvertising fail:" + JSON.stringify(error));
					}
				});
			},
			// 停止广播
			stopAdvertising() {
				console.log("停止广播");
				this.server.stopAdvertising({
					success(res) {
						console.log(res);
						wx.showToast({
							title: '广播已停止',
							icon: 'success'
						})
					}
				})
			}
		
		}
	}
</script>

<style>

</style>